<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="12">
          <a-col :md="4" :sm="8">
            <a-form-item label="车牌号">
              <a-input placeholder="请输入车牌号" v-model="queryParam.plateNo"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="2" :sm="4">
            <a-form-item>
              <a-date-picker placeholder="开始日期" v-model="queryParam.createTime_begin" @change="onChangeStartTime" />
            </a-form-item>
          </a-col>
          <a-col :md="2" :sm="4">
            <a-form-item>
              <a-date-picker placeholder="结束日期" v-model="queryParam.createTime_end" @change="onChangeEndTime" />
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" icon="reload" @click="searchReset" style="margin-left: 8px">重置</a-button>

            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExportXls('车辆入场信息')">导出</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchOut">
            <a-icon type="delete"/>
            出场
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>
    </div>
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择<a
          style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>
      <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          @change="handleTableChange"
          :rowSelection="{selectedRowKeys: selectedRowKeys,   onChange: onSelectChange,
           onSelect:onSelect,
            onSelectAll:onSelectAll,}"
          :customRow="handleCheck"
      >
        <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">详情</a>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->
    <!-- 表单区域 -->
    <inparkinglotCar-modal ref="modalForm" @ok="modalFormOk"></inparkinglotCar-modal>
    <inparkinglotCar-outBatch ref="outBatchForm" @ok="outBatchFormOk"></inparkinglotCar-outBatch>

  </a-card>
</template>

<script>
import inparkinglotCarModal from '../inparkinglotCar/modules/inparkinglotCarModal'
import inparkinglotCarOutBatch from '../inparkinglotCar/modules/inparkinglotCarOutBatch'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { deleteAction, getAction, downFile } from '@/api/manage'
import { filterObj } from '@/utils/util'
import parkInfoList from "@/components/parkInfoList";

import VuePreview from 'vue-preview'
export default {
  name: 'inparkinglotCarList',
  mixins: [JeecgListMixin],
  components: {
    inparkinglotCarModal,
    parkInfoList,
    inparkinglotCarOutBatch
  },
  data() {
    return {
      description: '车辆入场信息管理页面',
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: "",
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '停车场名称',
          align: 'center',
          dataIndex: 'parkName'
        },
        {
          title: '车牌号',
          align: 'center',
          dataIndex: 'plateNo'
        },
        {
          title: '车辆类型',
          align: 'center',
          dataIndex: 'carType',
          customRender: v => ('0' === v ? '无牌车' :'有牌车')
        },
        {
          title: '车辆性质',
          align: 'center',
          dataIndex: 'carNature',
          customRender: v =>{
            if(v==="0" || v===0){
              return "临时车";
            }else if(v==="1"||v===1){
              return "月租车";
            }else if(v==="2"||v===2){
              return "储值车";
            }else if(v==="3"||v===3){
              return "军警车";
            }else if(v==="4"||v===4){
              return "白名单";
            }else if(v==="5"){
              return "预约车";
            }
          },
        },
        {
          title: '入场时间',
          align: 'center',
          dataIndex: 'carEnterTime'
        },
        {
          title: '车辆进场地点',
          align: 'center',
          dataIndex: 'armName'
        },
        {
          title: '抓拍图片',
          align: 'center',
          dataIndex: 'imgPath',
          customRender: (record, row, index) => {
            let r = record
            return (
                <img
                    style="max-width:55px;max-height:55px;min-height:20px;min-width:20px;text-align:center;cursor:pointer;border:1px #BFBFBF solid;padding: 2px 2px 2px 2px;background-color:white;"
                    preview={r}
                    src={record}
                />
            )
          }
        },
        {
          title: '车辆状态',
          align: 'center',
          dataIndex: 'isOut',
          customRender: x => ('0' == x ? '未出场' : '已出场')
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        },
      ],
      url: {
        list: '/parking/inparkinglotCar/list',
        delete: '/parking/inparkinglotCar/delete',
        deleteBatch: '/parking/inparkinglotCar/deleteBatch',
        outBatch: '/parking/inparkinglotCar/outBatch',
        exportXlsUrl: 'parking/inparkinglotCar/exportXls',
        importExcelUrl: 'parking/inparkinglotCar/importExcel'
      },
      queryParam: {
        "createTime_begin": "",
        "createTime_end": "",
        "type": "-1",
      },
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      selectedRowKeys: [],
      selectedRows:[],
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  created() {
    this.keyupEnter()
  },
  methods: {
    onSelect (record, selected, selectedRows) {
      if (selected) {
        this.selectedRows.push(record);
      }

      if (!selected) {
        let delIndex = this.selectedRows.findIndex(val => {
          return val.id === record.id
        })
        this.selectedRows.splice(delIndex, 1);
      }
    },
    onSelectAll (selected, selectedRows, changeRows) {
      if (selected) {
        this.selectedRows = this.selectedRows.concat(changeRows);
      }

      if (!selected) {
        let selectedRows = JSON.parse(JSON.stringify(this.selectedRows));

        let delIndex = [];
        selectedRows.forEach((item, index) => {
          changeRows.forEach((val, itemIndex) => {
            if (item.id === val.id) {
              delIndex.push(index);
            }
          })
        })

        delIndex.forEach(item => {
          delete selectedRows[item];
        })

        selectedRows = selectedRows.filter(item => {
          return item != undefined;
        })
        this.selectedRows = selectedRows
      }
    },

    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys

    },
    handleCheck (record, index) {
      return {
        on: {
          click: e => {
            const checkIndex = this.selectedRowKeys.indexOf(record.id)
            if (checkIndex === -1) {
              this.selectedRowKeys.push(record.id)
              this.selectedRows.push(record)
            } else {
              this.selectedRowKeys.splice(checkIndex, 1)
              this.selectedRows.splice(checkIndex, 1)
            }
          }
        }
      }
    },
    searchReset(){
      this.queryParam =  {
        "createTime_begin": "",
        "createTime_end": "",
        "type": "-1",
      };
      this.$refs.parkInfoList.resetOption();
      this.loadData(1);
    },
    parkInfoListChange(parkCode) {
      this.queryParam.parkCode = parkCode;
    },
    daysBetween(sDate1, sDate2) {
      //Date.parse() 解析一个日期时间字符串，并返回1970/1/1 午夜距离该日期时间的毫秒数
      let time1 = Date.parse(new Date(sDate1).toDateString());
      let time2 = Date.parse(new Date(sDate2).toDateString());
      let nDays = Math.abs(parseInt((time2 - time1) / 1000 / 3600 / 24));
      return nDays;
    },
    handleExportXls(fileName) {
      let startTime = this.queryParam.createTime_begin
      let endTime = this.queryParam.createTime_end
      let opDesc = this.queryParam.opDesc
      let dayTime = startTime
      if (startTime == "") {
        this.$message.error('请选择导出开始日期')
        return
      }
      if (endTime == "") {
        this.$message.error('请选择导出结束日期')
        return
      }
      if (startTime != "" && endTime != "") {
        if (startTime > endTime) {
          this.$message.error('开始时间不能大于结束时间')
          return
        }
        if (this.daysBetween(startTime, endTime) + 1 > 15) {
          this.$message.error('仅支持15天数据导出,请选择导出日期')
          return
        }
      }

      if (startTime == "" && endTime != "") {
        this.$message.error('请选择开始时间')
        return
      }

      if (startTime != "" && endTime == "") {
        this.$message.error('请选择结束时间')
        return
      }

      this.queryParam.dayTime = dayTime
      fileName = dayTime + fileName
      let param = { ...this.queryParam }
      if (this.queryParam.createTime_begin != "" && this.queryParam.createTime_end != "") {
        param.createTime_begin = this.queryParam.createTime_begin + ' 00:00:00'
        param.createTime_end = this.queryParam.createTime_end + ' 23:59:59'
      }

      downFile(this.url.exportXlsUrl, param).then(data => {
        if (!data) {
          this.$message.error('文件下载失败')
          return
        }
        if(data.size===0){
          this.$message.warning("当前时段内没有车辆出场记录")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(url)
        }
      })
    },

    onChangeStartTime(date, dateString) {
      this.queryParam.createTime_begin = dateString
    },

    onChangeEndTime(date, dateString) {
      this.queryParam.createTime_end = dateString
    },

    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams()
      this.loading = true
      getAction(this.url.list, params).then(res => {
        if (res.success) {
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },

    searchQuery() {
      this.onClearSelected();
      let startTime = this.queryParam.createTime_begin
      let endTime = this.queryParam.createTime_end

      if (startTime != "" && endTime != "") {
        if (startTime > endTime) {
          this.$message.error('开始时间不能大于结束时间')
          return
        }
      }

      if (startTime == "" && endTime != "") {
        this.$message.error('请选择开始时间')
        return
      }

      if (startTime != "" && endTime == "") {
        this.$message.error('请选择结束时间')
        return
      }

      this.loadData(1)
    },

    getQueryParams() {
      var param = Object.assign({}, this.isorter, this.queryParam)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      if (this.queryParam.createTime_begin != "" && this.queryParam.createTime_end != "") {
        param.startTime = this.queryParam.createTime_begin + ' 00:00:00'
        param.endTime = this.queryParam.createTime_end + ' 23:59:59'
      }
      return filterObj(param)
    },

    outBatchFormOk(){
      this.loadData(1)
      this.onClearSelected();
    },

    onClearSelected: function () {
      this.selectedRowKeys = [];
      this.selectedRows = [];
    },

    //批量出场
    batchOut: function() {
      if (!this.url.outBatch) {
        this.$message.error('请设置url.outBatch属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        var plateNos = ""
        var parkCode = this.selectedRows[0].parkCode;
        console.log(this.selectedRows)
        console.log(this.selectedRows)
        for (var a = 0; a < this.selectedRows.length; a++) {
          plateNos += this.selectedRows[a].plateNo + ','
          if(parkCode != this.selectedRows[a].parkCode){
            this.$message.warning('请选择同一车场记录进行操作！')
            return;
          }
        }
        this.$refs.outBatchForm.title = '请选择车道信息'
        this.$refs.outBatchForm.form.resetFields();
        this.$refs.outBatchForm.batchEdit(plateNos,parkCode)
      }
    },

    batchDel: function() {
      if (!this.url.deleteBatch) {
        this.$message.error('请设置url.deleteBatch属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        var ids = ""
        for (var a = 0; a < this.selectionRows.length; a++) {
          ids += this.selectionRows[a].invateuserdetailId + ','
        }
        var that = this
        this.$confirm({
          title: '确认删除',
          content: '是否删除选中数据?',
          onOk: function() {
            deleteAction(that.url.deleteBatch, { ids: ids }).then(res => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          }
        })
      }
    },
    handleDelete: function(invateuserdetailId) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      var that = this
      deleteAction(that.url.delete, { invateuserdetailId: invateuserdetailId }).then(res => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    handleDetail: function(record) {
      this.$refs.modalForm.title = '详情'
      this.$refs.modalForm.edit(record)
    },

    keyupEnter() {
      document.onkeydown = e => {
        let body = document.getElementsByTagName('body')[0]
        if (e.keyCode === 13) {
          this.loadData(1)
        }
      }
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
